篇首语:本文由编程笔记#小编为大家整理,主要介绍了SpringBoot整合SpringSecurity相关的知识,希望对你有一定的参考价值。
之前写过一篇SSM整合SpringSecurity,没看过的可以看看,可以发现在SSM框架里整合Security框架是很繁琐的,所以很多人选择用Shiro搭配SSM使用。而在SpringBoot中,这个情况就不一样了,如果说是简单使用,只需要在SpringBoot项目中加入Security的依赖就可以了,不需要写什么其他的东西。
首先建一个SpringBoot项目,在pom文件中加入以下依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
为了看Security是否已被整合进SpringBoot&#xff0c;可以编写一个HelloController&#xff0c;如下&#xff1a;
&#64;Controller
public class HelloController
&#64;ResponseBody
&#64;GetMapping("/hello")
public String hello()
return "hello";
再接下来就可以启动项目了&#xff0c;在浏览器中访问localhost:8080/hello&#xff0c;此时会看到如下页面&#xff1a;
这里用户名为user&#xff0c;密码会在启动项目时打印到控制台&#xff0c;登录进去即可看到hello字符串。
我们使用SpringSecurity不可能每次都去重新生成一个密码&#xff0c;所以有以下几种策略来对帐户密码进行配置。
在application.properties文件中&#xff0c;加入以下代码即可自行配置SpringSecurity的帐户密码&#xff1a;
spring.security.user.name&#61;sang
spring.security.user.password&#61;123
spring.security.user.roles&#61;admin
这下启动程序后&#xff0c;就不会再生成一个密码了&#xff0c;登录账户就变成了sang&#xff0c;密码就变成了123&#xff0c;同时这个账户的角色是admin。
要是还是嫌配置文件配置的东西不够多&#xff0c;还可以使用配置类进行配置&#xff0c;首先新建一个类&#xff0c;比如叫MyWebSecurityConfig&#xff0c;这个类需要继承WebSecurityConfigurerAdapter&#xff0c;其代码如下&#xff1a;
&#64;Configuration
&#64;EnableGlobalMethodSecurity(prePostEnabled &#61; true, securedEnabled &#61; true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter
&#64;Bean
PasswordEncoder passwordEncoder()
// 加密算法
return new BCryptPasswordEncoder(10);
&#64;Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
// 在内存中配置账号密码
auth.inMemoryAuthentication()
// 账号
.withUser("admin")
// 密码【此处需要将密码加密】
.password(passwordEncoder().encode("123"))
// 账号的角色
.roles("ADMIN")
.and()
// 账号
.withUser("user")
// 密码【此处需要将密码加密】
.password(passwordEncoder().encode("123"))
// 账号的角色
.roles("USER")
;
&#64;Override
protected void configure(HttpSecurity http) throws Exception
http.authorizeRequests()
// 配置admin目录下的所有页面都需要ADMIN角色才能访问
.antMatchers("/admin/**").hasRole("ADMIN")
// 其他请求都需要验证权限
.anyRequest().authenticated()
.and()
// 开启表单登录
.formLogin()
// 登录处理URL
.loginProcessingUrl("/login")
// 允许登录页和登录处理链接不经过权限验证
.permitAll()
.and()
// 关闭csrf
.csrf().disable()
;
代码的解释都在注释里&#xff0c;接下来在HelloController中添加一个函数&#xff1a;
&#64;ResponseBody
&#64;GetMapping("/admin/hello")
public String adminHello()
return "hello admin";
启动程序&#xff0c;访问localhost:8080/hello&#xff0c;在登录页面尝试登录admin和user两个账号&#xff0c;都可以访问hello&#xff0c;而访问localhost:8080/admin/hello&#xff0c;则会发现只有admin账户才可访问&#xff0c;user账户没有权限。
像这种在内存中配置帐户密码的操作&#xff0c;在实际中并不实用&#xff0c;因为不可能每加个账户&#xff0c;就该代码并重启服务&#xff0c;所以要把数据库也整合进去&#xff0c;有关于数据库的整合&#xff0c;我写过一篇SpringBoot整合Mybatis的博客&#xff0c;不会的可以看一下。
首先我们需要从数据库中将数据拿出来&#xff0c;那么需要定义个实体类对象&#xff0c;用于接收拿到的数据&#xff0c;实体类有两个&#xff0c;一个是User&#xff0c;对应账户&#xff0c;一个是Role&#xff0c;对应角色&#xff1a;
User:
public class User implements UserDetails
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roles;
&#64;Override
public String toString()
return "User" &#43;
"id&#61;" &#43; id &#43;
", username&#61;&#39;" &#43; username &#43; &#39;\\&#39;&#39; &#43;
", password&#61;&#39;" &#43; password &#43; &#39;\\&#39;&#39; &#43;
", enabled&#61;" &#43; enabled &#43;
", locked&#61;" &#43; locked &#43;
", roles&#61;" &#43; roles &#43;
&#39;&#39;;
public User()
public User(Integer id, String username, String password, Boolean enabled, Boolean locked, List<Role> roles)
this.id &#61; id;
this.username &#61; username;
this.password &#61; password;
this.enabled &#61; enabled;
this.locked &#61; locked;
this.roles &#61; roles;
&#64;Override
public Collection<? extends GrantedAuthority> getAuthorities()
List<SimpleGrantedAuthority> authorities &#61; new ArrayList<>();
for(Role role:roles)
authorities.add(new SimpleGrantedAuthority(role.getName()));
return authorities;
&#64;Override
public String getPassword()
return password;
&#64;Override
public String getUsername()
return username;
&#64;Override
public boolean isAccountNonExpired()
return true;
&#64;Override
public boolean isAccountNonLocked()
return !locked;
&#64;Override
public boolean isCredentialsNonExpired()
return true;
&#64;Override
public boolean isEnabled()
return enabled;
public Integer getId()
return id;
public void setId(Integer id)
this.id &#61; id;
public void setUsername(String username)
this.username &#61; username;
public void setPassword(String password)
this.password &#61; password;
public void setEnabled(Boolean enabled)
this.enabled &#61; enabled;
public void setLocked(Boolean locked)
this.locked &#61; locked;
public List<Role> getRoles()
return roles;
public void setRoles(List<Role> roles)
this.roles &#61; roles;
注意User类实现了UserDetails接口&#xff0c;这是为了跟Security配合使用&#xff0c;以及User类中有个Role的列表&#xff0c;是为了在Security获取用户相关信息时&#xff0c;将用户的角色一起带过去。
Role:
public class Role
private Integer id;
private String name;
private String nameZh;
&#64;Override
public String toString()
return "Role" &#43;
"id&#61;" &#43; id &#43;
", name&#61;&#39;" &#43; name &#43; &#39;\\&#39;&#39; &#43;
", nameZh&#61;&#39;" &#43; nameZh &#43; &#39;\\&#39;&#39; &#43;
&#39;&#39;;
public Role()
public Role(Integer id, String name, String nameZh)
this.id &#61; id;
this.name &#61; name;
this.nameZh &#61; nameZh;
public Integer getId()
return id;
public void setId(Integer id)
this.id &#61; id;
public String getName()
return name;
public void setName(String name)
this.name &#61; name;
public String getNameZh()
return nameZh;
public void setNameZh(String nameZh)
this.nameZh &#61; nameZh;
有了实体类&#xff0c;接下来就是Mapper&#xff0c;也就是Dao层&#xff0c;首先是UserMapper接口&#xff1a;
&#64;Mapper
public interface UserMapper
User loadUserByUsername(String username);
List<Role> getUserRolesByUid(Integer id);
其对应的UserMapper.xml如下&#xff1a;
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace&#61;"com.alageek.study.mapper.UserMapper">
<select id&#61;"loadUserByUsername" parameterType&#61;"string" resultType&#61;"com.alageek.study.entity.User">
select * from user where username &#61; #username
select>
<select id&#61;"getUserRolesByUid" parameterType&#61;"integer" resultType&#61;"com.alageek.study.entity.Role">
select role.* from role, user_role where user_role.uid &#61; #id and user_role.rid &#61; role.id
select>
mapper>
然后在service层定义UserService&#xff1a;
&#64;Service
public class UserService implements UserDetailsService
&#64;Autowired
UserMapper userMapper;
&#64;Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException
User user &#61; userMapper.loadUserByUsername(s);
if(user &#61;&#61; null)
throw new UsernameNotFoundException("账户不存在");
user.setRoles(userMapper.getUserRolesByUid(user.getId()));
return user;
与User一样&#xff0c;为了配合Security使用&#xff0c;UserService需要实现接口UserDetailsService&#xff0c;其代码先根据用户名s获取到用户信息&#xff0c;再通过用户id获取到相关角色&#xff0c;再将组合后的用户信息返回。
有了Service后&#xff0c;还需要在Security的配置类中进行相关配置&#xff0c;代码如下&#xff1a;
&#64;Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
auth.userDetailsService(userService);
在配置类中加入上述代码即可&#xff0c;就能从数据库中获取账户数据进行比对&#xff0c;从而登录&#xff0c;而注册只需往数据库中插入数据即可。
写完上述数据库相关代码后&#xff0c;测试功能跟上面一样&#xff0c;写一个Controller启动项目登录下试试即可。
源码没有跟博客说的一模一样&#xff0c;不过我觉得能看到这里的小伙伴&#xff0c;借鉴应该是没有问题的&#xff0c;加油&#xff0c;一起学习吧&#xff0c;有什么问题请在评论说出来。